package GameDb.Task;

import GameDb.JDBC.JDBCTemplate;
import GameDb.Task.common.DbTask;
import Protobuf.DbProto;
import io.netty.channel.ChannelHandlerContext;

import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author jedi
 */
public class ServerInit implements DbTask {

    private final ChannelHandlerContext ctx;

    public ServerInit(ChannelHandlerContext ctx){
        this.ctx = ctx;
    }

    @Override
    public void run(Connection conn) throws Exception {
        List<DbProto.Msg> list = new ArrayList<>();
        String sql = "SELECT id,username FROM user";
        JDBCTemplate jdbcTemplate = new JDBCTemplate();
        List<Map<String,Object>> dbList = jdbcTemplate.getList(conn,sql);
        for(Map<String,Object> map:dbList){
            long id =Long.parseLong(map.get("id").toString());
            String username = (String) map.get("username");
            System.out.println(id+" "+username);
            DbProto.Msg playerMsg = DbProto.Msg.newBuilder().setMsgType(DbProto.Msg.MsgType.init)
                    .setPlayer(DbProto.Player.newBuilder().setId(id).setUsername(username).build())
                    .build();
            list.add(playerMsg);
        }
        for(DbProto.Msg idMsg:list){
            ctx.write(idMsg);
        }
        ctx.flush();
    }


}
